import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { ref, onMounted, h } from "vue";
import { dealDataExcept, dealDataRide } from "@/utils/common";
import { useRoute } from "vue-router";
import { addDialog } from "@/components/ReDialog";
import dayjs from "dayjs";
import { UpOrderGoods } from "./components";
import { DictTag } from "@/components/common/DictTag";
import { goodsNameRend, goodsCodeRend } from "@/utils/tableColumns";
// api
import {
  getStoreOrderDetail,
  upStoreOrderStatus,
  upStoreOrder,
  cancelSupplierDelivery,
  cancelWareHouseDelivery,
  getSupplierDeliveryList,
  getWareHouseDeliveryList
} from "@/api/orderManag/purchaseOrder";
import { cloneDeep } from "@pureadmin/utils";

const isUpdate = ref(false);
export function useStoreOrderDetail(detailType: number) {
  const currentRoute = useRoute();
  const isStoreManager = ref(0); // 是否驻店店长角色
  const storeForm = ref<any>({});
  const orderForm = ref<any>({
    deliveryList: [],
    depository: {}
  });
  const loading = ref(false);
  const stepIndex = ref(1);
  // 子订单状态 0 待审核 1待确认 2已确认 3 配货中 4 部分发货 5 已发货 6 已完成 7 已关闭
  const stepList = ref([
    {
      title: "待确认",
      description: ""
    }
  ]);
  const goodsColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "goodsName",
      minWidth: 200,
      align: "left",
      fixed: "left",
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "goodsCode",
      align: "left",
      minWidth: 150,
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品条码",
      prop: "barCode",
      minWidth: 120,
      formatter: row => row.barCode || "--"
    },
    {
      label: "关联供应商",
      prop: "supplierName",
      minWidth: 120,
      formatter: ({ supplierName }) => supplierName || "--"
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "数量",
      prop: "goodsAmount",
      minWidth: 100
    },
    {
      label: "已入库数量",
      prop: "storeAmount",
      minWidth: 100
    },
    {
      label: "待入库数量",
      prop: "stayStoreAmount",
      minWidth: 100
    }
  ];

  // 发货表格列
  let deliveryGoodsColumns = cloneDeep(goodsColumns).slice(0, 6);

  // 合计行
  const getSummaries = param => {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if ([5, 8, 9].includes(index)) {
        // 计算金额
        let sumVal = 0;
        if (index == 5) {
          data.forEach(
            v => (sumVal += dealDataRide(v.goodsAmount, v.buyPrice))
          );
          sumVal = dealDataExcept(sumVal);
        } else {
          sumVal = data
            .map(item => Number(item[column.property]))
            .reduce((prev, curr) => prev + curr, 0);
        }
        sums[index] = sumVal;
      }
    });

    return sums;
  };

  // 获取订单状态 primary success danger
  const getOrderStatus = status => {
    if (status == null) {
      return "--";
    }

    // 子订单状态 0 待审核 1待确认 2已确认 3 配货中 4 部分发货 5 已发货 6 已完成 7 已关闭
    let statusMap = {
      0: { text: "待审核", type: "warning" },
      1: { text: "待确认", type: "warning" },
      2: { text: "已确认", type: "success" },
      3: { text: "配货中", type: "primary" },
      4: { text: "部分发货", type: "success" },
      5: { text: "已发货", type: "success" },
      6: { text: "已完成", type: "success" },
      7: { text: "已关闭", type: "danger" }
    };
    let obj = statusMap[status];
    return obj.text;
  };

  // 审核状态 1 通过 2驳回 3 取消订单
  const handleOpt = async (row, opt) => {
    let params = {
      id: row.id,
      auditStatus: opt
    };
    await upStoreOrderStatus(params);
    let status = opt == 1 ? 1 : opt == 2 ? 5 : 6;
    row.status = status;
    message("操作成功", { type: "success" });
    isUpdate.value = true;
    getOrderDetail();
  };

  // 作废
  const doCancel = async (item, index) => {
    // detailType 1: 仓库详情  2: 供应商详情
    detailType == 1
      ? await cancelWareHouseDelivery({ deliveryCode: item.deliveryCode })
      : await cancelSupplierDelivery({
          num: item.num,
          suborderId: orderForm.value.id
        });
    console.log(index);
    item.status = 1;
    // orderForm.value.deliveryList.splice(index, 1);
    message("作废成功", { type: "success" });
  };

  // 处理步骤条的显示
  const dealSetpList = data => {
    let orderStatusList = data.storeSuborderStatusResponses || [];
    // orderStatusList = [
    //   { orderStatus: 0, gmtCreate: "2024-12-05 17:19:16" },
    //   { orderStatus: 1, gmtCreate: "2024-12-06 17:19:16" },
    //   { orderStatus: 2, gmtCreate: "2024-12-07 17:19:16" },
    //   { orderStatus: 3, gmtCreate: "2024-12-08 17:19:16" },
    //   { orderStatus: 4, gmtCreate: "2024-12-09 17:19:16" }
    // ];

    // 对数组进行排序
    orderStatusList.sort((a, b) => {
      return a.orderStatus - b.orderStatus;
    });

    // 初始化 list
    let tempStepList = [
      {
        title: "待确认",
        description: dayjs(data.gmtCreate).format("YYYY-MM-DD HH:mm")
      }
    ];

    // 判断当前订单流程是否已经结束
    let isCancel = orderStatusList.findIndex(v =>
      [6, 7].includes(v.orderStatus)
    );
    if (isCancel == -1) {
      // 流程没有结束则展示待完成的节点
      tempStepList = [
        {
          title: "待确认",
          description: dayjs(data.gmtCreate).format("YYYY-MM-DD HH:mm")
        },
        {
          title: "已确认",
          description: ""
        },
        {
          title: "配货中",
          description: ""
        },
        {
          title: "部分发货",
          description: ""
        },
        {
          title: "已发货",
          description: ""
        },
        {
          title: "已完成",
          description: ""
        }
      ];
      // 子订单状态 1 待确认 2 已确认 3 配货中 4 部分发货 5 已发货 6 已完成 7 已关闭
      orderStatusList.forEach(v => {
        let dateStr = dayjs(v.gmtCreate).format("YYYY-MM-DD HH:mm");
        tempStepList[v.orderStatus - 1].description = dateStr;
      });
      stepIndex.value =
        orderStatusList.length > 0
          ? orderStatusList[orderStatusList.length - 1].orderStatus
          : 1;
      stepList.value = tempStepList;
    } else {
      // 子订单状态 1 待确认 2 已确认 3 配货中 4 部分发货 5 已发货 6 已完成 7 已关闭
      let orderStatusMap = {
        1: "待确认",
        2: "已确认",
        3: "配货中",
        4: "部分发货",
        5: "已发货",
        6: "已完成",
        7: "已关闭"
      };
      orderStatusList.forEach(v => {
        tempStepList.push({
          title: orderStatusMap[v.orderStatus],
          description: dayjs(v.gmtCreate).format("YYYY-MM-DD HH:mm")
        });
      });
      stepIndex.value = tempStepList.length;
      stepList.value = tempStepList;
    }
  };

  // 修改商品的数量
  const upOrderGoodsRef = ref();
  const upOrderGoods = (orderForm, page) => {
    return new Promise(resolve => {
      let newCloums = cloneDeep(goodsColumns).slice(0, 6);
      newCloums[4].slot = "amount";
      newCloums[4].width = 220;
      newCloums[5].width = 150;
      addDialog({
        title: "修改订单",
        props: {
          goodsColumns: newCloums,
          goodsList: cloneDeep(orderForm.orderItemResponses || []),
          getSummaries
        },
        width: "1100px",
        draggable: true,
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => h(UpOrderGoods, { ref: upOrderGoodsRef }),
        beforeSure: async done => {
          ElMessageBox.confirm("是否确认修改商品数量?", "系统提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            dangerouslyUseHTMLString: true,
            draggable: true
          }).then(async () => {
            let newGoodsList = upOrderGoodsRef.value.getGoodsList();
            let params = {
              storeOrderCode: orderForm.storeOrderCode,
              shoppingCartUpdateRequest: newGoodsList.map(v => {
                return {
                  goodsId: v.goodsId,
                  amount: v.goodsAmount
                };
              })
            };
            await upStoreOrder(params);
            if (page == 2) {
              isUpdate.value = true;
            }
            message("修改成功", { type: "success" });
            done();
            resolve(true);
          });
        },
        beforeCancel: done => {
          done();
        }
      });
    });
  };

  const getOrderDetail = async () => {
    let orderId = currentRoute.query?.id;
    if (orderId) {
      loading.value = true;

      let parasm = {
        bizType: 1,
        subOrderId: orderId
      };
      let { data } = await getStoreOrderDetail(parasm).catch(() => {
        loading.value = false;
      });
      // data.billNoDetailResponses = [
      //   {
      //     id: 1,
      //     gmtCreate: "2024-12-07 15:00:00",
      //     itemList: [
      //       {
      //         ftime: "2024-12-07 15:00",
      //         context: "内容1"
      //       },
      //       {
      //         ftime: "2024-12-07 15:00",
      //         context: "内容1"
      //       }
      //     ]
      //   },
      //   {
      //     id: 2,
      //     gmtCreate: "2024-12-07 15:00:00",
      //     itemList: [
      //       {
      //         ftime: "2024-12-07 15:00",
      //         context: "内容2"
      //       }
      //     ]
      //   }
      // ];

      // 获取发货信息
      // detailType 1: 仓库详情  2: 供应商详情
      let deReq =
        detailType == 1
          ? await getWareHouseDeliveryList({ subOrderId: orderId })
          : await getSupplierDeliveryList({ subOrderId: orderId });
      let tempDeliveryList =
        deReq.data.deliveryResponses || deReq.data.stashListResponses || [];
      tempDeliveryList = tempDeliveryList.reverse();
      data.deliveryList = tempDeliveryList.sort((a, b) => {
        return a.status - b.status;
      });

      data.depository = deReq.data.depositoryResponse || {};

      // 处理步骤条
      dealSetpList(data);
      orderForm.value = data;
      loading.value = false;
    }
  };

  onMounted(async () => {
    getOrderDetail();
  });

  return {
    loading,
    goodsColumns,
    deliveryGoodsColumns,
    orderForm,
    isStoreManager,
    stepIndex,
    stepList,
    isUpdate,
    storeForm,
    getSummaries,
    getOrderStatus,
    handleOpt,
    upOrderGoods,
    getOrderDetail,
    doCancel
  };
}
